#!/usr/bin/env python
#coding=utf-8

import re
from common.tools import Tools
import sys
import json 
import cStringIO
import wx

def demo(f):
    #自动保存网页的模板
    Tools.saveToFile('error', f.read(), 'xml_parse_error(%s)' % sys._getframe().f_code.co_name)

def helper(filename, reg):
    #辅助测试
    f = open(filename, 'r')
    data = f.read()
    p = re.compile(reg, re.IGNORECASE)
    m = p.search(data)  
    print m   
    
def parseHelper(data, reg, result, *args):    
    p = re.compile(reg, re.IGNORECASE)
    m = p.search(data)    
    if m:
        for name in args:
            result[name] = m.group(name)  
            
def parseMain(f): 
    result = {}
    if f:
        data = f.read()
        
        reg = r'<div class="forget01" style="color:#cc3300; text-align:left;">(?P<error>.*?)</div>' 
        parseHelper(data, reg, result, 'error')   
         
        if not result:    
            #login success 
            reg = r'<a href="home!other\.do\?id=(?P<id>\d+)">(?P<name>.*?)</a>' 
            parseHelper(data, reg, result, 'id', 'name')
            
            reg = r'<div class="l" style="font-weight:normal;">积分：<a href="popularity!listintegral.do"><span id="_INTEGRAL" style="font-weight:normal;color:#3b5888;">(?P<jifen>\d+)</span></a></div>' 
            parseHelper(data, reg, result, 'jifen')    
        
            reg = r'<div class="l" style="font-weight:normal;">金豆：<a href="popularity!listUseRecords.do"><span id="_SNSMONEY" style="font-weight:normal;color:#3b5888;">(?P<jindou>\d+)</span></a></div>' 
            parseHelper(data, reg, result, 'jindou')      
            
            reg = r'<div class="l" style="font-weight:normal;">人气：<a href="popularity!todaypop.do">(?P<renqi>\d+)</a></div>' 
            parseHelper(data, reg, result, 'renqi')      
            
            if result:
                result['error'] = ''
    return result

def parseFriendsList(f):
    result = []
    if f:
        data = f.read() 
        #获得有好友列表的区域
        reg = '<div class="hylist_nr" style="margin:0px;">(?P<friendsContent>[\s\S]*?)<!--xiangcejieshu-->'
        p = re.compile(reg, re.IGNORECASE)
        m = p.search(data)
        if m:
            data = m.group('friendsContent')
            #解析好友
            reg = r'<a href="home!other\.do\?id=(?P<id>\d+)">(?P<name>[^<>].*?)</a>' 
            p = re.compile(reg, re.IGNORECASE)
            m = p.findall(data)         
            if m:
                m = [dict(id=i[0], name=i[1]) for i in m]
                result = m
    return result

#########blog###################
def parseMyBlogList(f):
    result = {}
    if f:
        data = f.read()    
        reg = r'<a href="blog!MyCategoryBlog\.do\?id=(?P<id>\d+)" class="a0">未分类</a>' 
        parseHelper(data, reg, result, 'id') 
    return result     

def parsePostBlog(f):
    if f:   
        data = f.read()     
        try:
            jsn = json.loads(data)
            return jsn['blogID']
        except ValueError, KeyError:
            return 0
    else:
        return 0

def parseBlogList(f):
    #取得当天的最新的日志    
    result = {}
    if f:
        data = f.read()    
        reg = r'<a href="javascript:checkPrivate\((?P<blogid>\d+),(?P<id>\d+),true\)" id="blogHref\d+">(?P<title>[\s\S]*?)</a></dd>[\s\S]*?<dd style="width:100px;">.*?</dd>[\s\S]*?<dd style="width:105px;text-align:right;">(?P<time>[^-:]*?)</dd>' 
        parseHelper(data, reg, result, 'blogid', 'id', 'title', 'time')
        if result:
            result['title'] = result['title'].replace('<img src="images/yuanc.gif">', '').strip()
    return result  

def parseSaveBlogError(f): 
    r = {}  
    if f:
        data = f.read()     
        try:
            jsn = json.loads(data)
            if jsn.has_key('error'):#留言出现异常
                error = jsn['error']
                r = dict(state=0, info=Tools.unicodeToHanzi(error))
            elif jsn.has_key('score'):#留言加了人气
                r = dict(state=1, info=jsn['score'])
            elif jsn.has_key('state'):#留言没加人气
                r = dict(state=2, info='')     
        except ValueError, KeyError:
            pass
    return r

###########MiniBlog#############    
def parsePostTwitter(f): 
    if f:  
        data = f.read()     
        try:
            jsn = json.loads(data)
            return jsn['miniid']
        except ValueError, KeyError:
            return 0
    else:
        return 0

def parseMiniBlogList(f):
    #取得当天的最新的mini日志    
    result = {}
    if f:
        data = f.read()    
        reg = r'<div class="mini_title">[\s\S]*?<div class="l"><span class="gray">[^-:]*?</span></div>[\s\S]*?<div class="r"><a href="miniblog!showMiniBlog\.do\?id=(?P<id>\d+)&userId=(?P<userId>\d+)">[^<>].*?</a></div>[\s\S]*?</div>' 
        parseHelper(data, reg, result, 'id', 'userId')
    return result 
        
def parseSaveMiniBlogError(f): 
    return parseSaveBlogError(f)
    
###########daka#############    
def parseDaka(f):  
    r = {} 
    if f:
        data = f.read()     
        try:
            jsn = json.loads(data)
            if jsn.has_key('error'):#没有三次互动过
                error = jsn['error']
                r = dict(state=0, info=Tools.unicodeToHanzi(error))            
            if jsn.has_key('r'):
                if jsn['r'] == 0:#打卡成功
                    r = dict(state=1, info=jsn['nowintegral'])
                elif jsn['r'] == 2:#已经打过卡
                    r = dict(state=2, info='')
        except ValueError, KeyError:
            pass
    return r

###########小号申请######################    
def parseInviteList(f):
    result = {}
    if f:
        data = f.read()    
        reg = r'<div class="dash c3" style="line-height:50px;background:#FCF9E6;padding-left:5px;" id="invitecode">http://www\.yy365\.com/invite!from\.do\?id=(?P<id>[^&]*?)&&code=(?P<code>[^<>]\d+) </div>' 
        parseHelper(data, reg, result, 'id', 'code')
        reg = r'<div class="head_menu01"><a href="home!other\.do\?id=(?P<sid>[^<>]\d+)">' 
        parseHelper(data, reg, result, 'sid')
    return result 

def parseRetrieveImg(f):
    imgSrc = ''
    if f:
        data = f.read()     
        try:
            jsn = json.loads(data)
            imgSrc = jsn['imgSrc']    
        except ValueError, KeyError:
            pass
    return imgSrc

def getImageFromWeb(f):
    if f:
        data = f.read()
        try:        
            stream = cStringIO.StringIO(data)
            image = wx.ImageFromStream(stream)
            return image
        except:
            f.seek(0)
            Tools.saveToFile('error', f.read(), 'image_parse_error(%s)' % sys._getframe().f_code.co_name)

def parseReg(f):    
    exception = ''
    if f:
        data = f.read()     
        try:
            jsn = json.loads(data)
            exception = Tools.unicodeToHanzi(jsn['exception'])   
        except ValueError, KeyError:
            pass
    return exception  
      
def parseEmail(f):  
    exists = -1
    if f:
        data = f.read()     
        try:
            jsn = json.loads(data)
            exists = jsn['exists']   
        except ValueError, KeyError:
            pass
    return exists  
    
if __name__ == '__main__':
    f = open(r'file/email.txt', 'r')
    data = parseEmail(f) 
    if data:
        print data
    else:
        print '23'  
    
